package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.VideoItem;
import com.onlinevideo.service.impl.VideoItemServiceImpl;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class VideoItemServlet extends BaseServlet {

    private PrintWriter writer = null;
    VideoItemServiceImpl videoItemService = new VideoItemServiceImpl();

    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<FileItem> fileItems = (List<FileItem>) req.getAttribute("fileList");
        VideoItem videoItem = videoItemService.insert(fileItems);
        if (videoItem != null) {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("数据添加成功", videoItem)));
        } else {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("数据添加失败")));
        }

    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        Long videoItemId = Long.valueOf(req.getParameter("videoItemId"));
        int delete = videoItemService.delete(videoItemId);
        if (delete > 0) {
            writer.write("1");
        } else {
            writer.write("0");
        }
    }

    protected void updateInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        String videoItemIdStr = req.getParameter("videoItemId");
        String sortCountStr = req.getParameter("sortCount");
        String name = req.getParameter("name");
        if (!sortCountStr.matches("[1-9]+")) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("数据格式有问题")));
            return;
        }
        Long videoItemId = Long.valueOf(videoItemIdStr);
        Integer sortCount = Integer.valueOf(sortCountStr);
        int update = videoItemService.update(name, sortCount, videoItemId);

        if (update>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("修改成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("修改失败")));
        }


    }
}
